package org.altervista.cp.microkernel.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;

public class BinaryContent implements Blob {

	public void free() throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public InputStream getBinaryStream() throws SQLException {
		return _is;
	}

	public InputStream getBinaryStream(long pos, long length)
			throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public byte[] getBytes(long pos, int length) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public long length() throws SQLException {
		return _tf.length();
	}

	public long position(byte[] pattern, long start) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public long position(Blob pattern, long start) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public OutputStream setBinaryStream(long pos) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public int setBytes(long pos, byte[] bytes) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public int setBytes(long pos, byte[] bytes, int offset, int len)
			throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public void truncate(long len) throws SQLException {
		throw new SQLFeatureNotSupportedException();
	}

	public BinaryContent(TemporaryFile tf) {
		_tf = tf;
	}

	public void setContent(InputStream is) throws IOException {
		_tf.readFrom(is);
	}

	public void setContent(Reader r, String charset) throws IOException {
		new BufferedIO().copy(charset, r, _tf.getOutputStream());
	}

	public void setContent(Reader r) throws IOException {
		new BufferedIO().copy(r, _tf.getOutputStream());
	}

	public void setContent(Serializable s) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(_tf.getOutputStream());
		oos.writeObject(s);
		oos.close();
	}

	public InputStream getInputStream() throws IOException {
		return _tf.getInputStream();
	}

	public long getLength() {
		return _tf.length();
	}

	public Blob getBlob() {
		return new Blob() {

			private InputStream _is;

			{
				try {
					_is = getInputStream();
				} catch (IOException e) {
					throw new IllegalStateException(e);
				}
			}
		};
	}

	private TemporaryFile _tf;
}
